package com.guc.coroutines.animator

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.View

/**
 * Created by guc on 2021/9/22.
 * Description：
 */
class PointAnimView(context: Context, attrs: AttributeSet?, defStyleAttr: Int = 0) :
    View(context, attrs, defStyleAttr) {
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context) : this(context, null, 0)

    private var radius: Float = 0f
    private val linePath = Path()
    private var isPlaying = false
    private var mPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.BLACK
        strokeWidth = 5f
        style = Paint.Style.STROKE
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.let {
            it.drawPath(linePath, mPaint)
        }
    }

    fun startLineAnimator() {
        if (isPlaying) return
        radius = (height  / 2).toFloat()
        val startP = Point(0, 0)
        val endP = Point(width, height)
        ValueAnimator.ofObject(PointSinEvaluator(), startP, endP).apply {
            repeatCount = -1
            duration = 5000
            addUpdateListener {
                it.animatedValue.apply {
                    if (this is Point) {
                        if (this.x == 0) {
                            linePath.reset()
                            linePath.moveTo(0f, height / 2f)
                        } else {
                            linePath.lineTo(this.x.toFloat(), this.y.toFloat())
                        }
                        postInvalidate()
                    }
                }
            }
            start()
        }
        isPlaying = true

    }

}